﻿using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using KeRui.Common;
using System.Text;
using System.Collections.Generic;
using System.Text.RegularExpressions;

public partial class Manage_Admin_AdminItem : System.Web.UI.Page
{
    protected int AccountID = PageRequest.GetInt("id", -1);
    public string Act = ManageHelper.PageAct();
    private KeRui.BLL.Account bllAccount = new KeRui.BLL.Account();
    protected KeRui.Model.Account modelAccount = new KeRui.Model.Account();
    private ManageErrMsg nsb = new ManageErrMsg();
    protected string ActFlag = "addsave";
    protected string ActName = "添加";

    protected KeRui.BLL.Admin bllAdmin = new KeRui.BLL.Admin();
    protected KeRui.Model.Admin modelAdmin = new KeRui.Model.Admin();

    protected KeRui.BLL.CmsSite bllCmsSite = new KeRui.BLL.CmsSite();
    protected void Page_Load(object sender, EventArgs e)
    {
        ManageHelper.CheckAdminLogin();
        switch (Act)
        {
            case "addsave":
                Add();
                break;
            case "edit":
                Edit();
                break;
            case "editsave":
                EditSave();
                break;
            case "del":
                Del();
                break;
            case "state":
                State();
                break;
            case "csrf":
                ChageSiteRoleFlagState();
                break;
            case "showsite":
                showSite();
                break;
            case "showadditionalrights":
                ShowAdditionalrights();
                break;
            default:
                break;
        }
    }

    #region 添加
    private void Add()
    {
        ManageHelper.CheckAdminPower("system_adminadd");//权限
        modelAdmin.Username = PageRequest.GetString("userName");
        if (modelAdmin.Username == "")
        {
            nsb.AddErr("请输入用户名。");
        }
        modelAdmin.RealName = PageRequest.GetString("RealName");
        string Password = Utils.MD5(PageRequest.GetString("password"));
        string ChkPassword = Utils.MD5(PageRequest.GetString("Chkpassword"));
        if (Password == "")
        {
            nsb.AddErr("请输入密码。");
        }
        if (ChkPassword != Password)
        {
            nsb.AddErr("两次输入密码不一致。");
        }
        modelAdmin.CreateIP = Utils.GetRealIP();
        modelAdmin.RoleIDs = PageRequest.GetString("RoleIDs");//角色
        #region 根据角色 获取权限 RoleFlags &&  RoleNames
        modelAdmin.RoleFlags = "";
        modelAdmin.RoleNames = "";
        KeRui.BLL.AdminRole bllAdminRole = new KeRui.BLL.AdminRole();
        List<KeRui.Model.AdminRole> listAdminRole = bllAdminRole.GetList(modelAdmin.RoleIDs);
        foreach (KeRui.Model.AdminRole model in listAdminRole)
        {
            if (model.RoleFlag != "")
            {
                modelAdmin.RoleFlags += model.RoleFlag + ",";
                modelAdmin.RoleNames += model.RoleName + ",";
            }
        }
        if (modelAdmin.RoleFlags != "" && modelAdmin.RoleFlags != null)
        {
            modelAdmin.RoleFlags = modelAdmin.RoleFlags.Substring(0, modelAdmin.RoleFlags.Length - 1);
            modelAdmin.RoleNames = modelAdmin.RoleNames.Substring(0, modelAdmin.RoleNames.Length - 1);
        }
        #endregion
        modelAdmin.PlusFlag = PageRequest.GetString("SiteID");//额外站点权限
        modelAdmin.UserFlag = modelAdmin.PlusFlag;
        if (modelAdmin.RoleFlags != "")
        {
            if (modelAdmin.PlusFlag != "")
            {
                modelAdmin.UserFlag = modelAdmin.RoleFlags + "," + modelAdmin.PlusFlag;
            }
            else
            {
                modelAdmin.UserFlag = modelAdmin.RoleFlags;
            }
        }

        modelAdmin.State = PageRequest.GetInt("State", 0);
        nsb.ChkErr();

        int resInt = bllAdmin.Add(modelAdmin, Password);
        if (resInt == -1)
        {
            nsb.AddErr("该管理员已经存在。");
            nsb.ChkErr();
        }
        else
        {
            ManageHelper.AddLog("system_adminadd", "添加了“" + modelAdmin.Username + "”管理员。");//写日志
            Response.Redirect("AdminItem.aspx?sucmsg=添加成功。");
        }
    }
    #endregion

    #region 反显修改页面
    private void Edit()
    {
        ActFlag = "editsave";
        ActName = "修改";
        int UserID = PageRequest.GetInt("ID", -1);
        if (UserID == -1)
        {
            nsb.AddErr("该站点不存在。");
            nsb.ChkErr();
        }
        modelAdmin = bllAdmin.GetModel(UserID);
        modelAccount = bllAccount.GetModel(UserID);
    }
    #endregion

    #region 修改时保存
    private void EditSave()
    {
        modelAdmin.UserID = PageRequest.GetInt("UserID", -1);
        if (modelAdmin.UserID == -1)
        {
            nsb.AddErr("Error：没有找到UserID"); nsb.ChkErr();
        }

        if (modelAdmin.UserID != KeRui.BLL.Account.GetLoginAdminID())
        {
            ManageHelper.CheckAdminPower("system_adminedit");//权限
        }

        modelAdmin.Username = PageRequest.GetString("userName");
        if (modelAdmin.Username == "")
        {
            nsb.AddErr("请输入用户名。");
        }
        modelAdmin.RealName = PageRequest.GetString("RealName");
        string Password = PageRequest.GetString("password");
        string ChkPassword = PageRequest.GetString("Chkpassword");

        if (Password != "")
        {
            if (ChkPassword != Password)
            {
                nsb.AddErr("两次输入密码不一致。");
            }
            Password = Utils.MD5(Password);
        }
        else
        {
            Password = bllAccount.GetModel(modelAdmin.UserID).Password;
        }

        modelAdmin.CreateIP = Utils.GetRealIP();
        modelAdmin.RoleIDs = PageRequest.GetString("RoleIDs");//角色
        #region 根据角色 获取权限 RoleFlags &&  RoleNames
        modelAdmin.RoleFlags = "";
        modelAdmin.RoleNames = "";
        KeRui.BLL.AdminRole bllAdminRole = new KeRui.BLL.AdminRole();
        List<KeRui.Model.AdminRole> listAdminRole = bllAdminRole.GetList(modelAdmin.RoleIDs);
        foreach (KeRui.Model.AdminRole model in listAdminRole)
        {
            if (model.RoleFlag != "")
            {
                modelAdmin.RoleFlags += model.RoleFlag + ",";
                modelAdmin.RoleNames += model.RoleName + ",";
            }
        }
        if (modelAdmin.RoleFlags != "" && modelAdmin.RoleFlags != null)
        {
            modelAdmin.RoleFlags = modelAdmin.RoleFlags.Substring(0, modelAdmin.RoleFlags.Length - 1);
            modelAdmin.RoleNames = modelAdmin.RoleNames.Substring(0, modelAdmin.RoleNames.Length - 1);
        }
        #endregion

        #region 额外站点权限
        modelAdmin.PlusFlag = "";//额外站点权限
        KeRui.Model.Admin modelAdmin_old = bllAdmin.GetModel(modelAdmin.UserID);
        KeRui.BLL.CmsSite bllCmsSite = new KeRui.BLL.CmsSite();
        modelAdmin_old.PlusFlag = "," + modelAdmin_old.PlusFlag + ",";
        string pattern = @"site_\d+";
        Regex regex = new Regex(pattern);
        MatchCollection collection = regex.Matches(modelAdmin.RoleFlags);
        string xs = ",";//得到当前所拥有的网站
        foreach (Match match in collection)
        {
            xs += match.Captures[0].ToString() + ",";
        }
        xs = xs + PageRequest.GetString("SiteID");

        modelAdmin.PlusFlag = modelAdmin_old.PlusFlag;
        List<KeRui.Model.CmsSite> list = bllCmsSite.GetList();
        foreach (KeRui.Model.CmsSite model in list)
        {
            if (xs.IndexOf(",site_" + model.SiteID + ",") == -1)//选择中  不存在
            {
                if (modelAdmin_old.UserFlag.IndexOf(",site_" + model.SiteID + ",") != -1)//数据库中    存在
                {//过滤数据
                    string _pattern = @"site\w*?_" + model.SiteID + "";
                    Regex regex1 = new Regex(_pattern);
                    MatchCollection collection1 = regex1.Matches(modelAdmin_old.PlusFlag);
                    foreach (Match match in collection1)
                    {
                        //把站点权限全部找出来
                        modelAdmin.PlusFlag = modelAdmin.PlusFlag.Replace(match.Captures[0].ToString(), "").Replace(",,", ",");
                    }
                }
            }
        }
        modelAdmin.PlusFlag = modelAdmin.PlusFlag + PageRequest.GetString("SiteID");
        #endregion

        #region UserFlag
        modelAdmin.UserFlag = modelAdmin.PlusFlag;
        if (modelAdmin.RoleFlags != "")
        {
            if (modelAdmin.PlusFlag != "")
            {
                modelAdmin.UserFlag = modelAdmin.RoleFlags + "," + modelAdmin.PlusFlag;
            }
            else
            {
                modelAdmin.UserFlag = modelAdmin.RoleFlags;
            }
        }
        #endregion
        modelAdmin.State = PageRequest.GetInt("State", 0);
        nsb.ChkErr();
        int RetFlag = bllAdmin.Update(modelAdmin, Password);
        if (RetFlag == 1)
        {
            nsb.AddErr("对不起！已存在相同的用户名。");
            nsb.ChkErr();
        }
        else
        {
            ManageHelper.AddLog("system_adminedit", "修改了“" + modelAdmin.Username + "”管理员。");//写日志
            Response.Redirect("adminItem.aspx?act=edit&id=" + modelAdmin.UserID + "&sucmsg=修改成功。");
        }
    }
    #endregion

    #region 删除
    private void Del()
    {
        ManageHelper.CheckAdminPower("system_admindelete");//权限
        int UserID = PageRequest.GetInt("ID", -1);
        if (UserID == -1)
        {
            nsb.AddErr("该管理员不存在。");
            nsb.ChkErr();
        }
        bllAdmin.Delete(UserID);
        ManageHelper.AddLog("system_admindelete", "删除了“" + modelAdmin.Username + "”管理员。");//写日志
        Response.Redirect("adminList.aspx?sucmsg=恭喜。删除成功。");
    }
    #endregion

    #region 解锁和锁定
    private void State()
    {
        KeRui.BLL.Member bllMember = new KeRui.BLL.Member();
        int UserID = PageRequest.GetInt("ID", -1);
        int st = PageRequest.GetInt("st", 0);
        if (UserID == -1)
        {
            nsb.AddErr("对不起。你想要操作的用户不存在。");
            nsb.ChkErr();
        }
        int RetInt = bllMember.ChageState(UserID, 1);
        if (st == 1)
        {
            Response.Redirect("AdminList.aspx?sucmsg=恭喜。锁定成功。");
        }
        else
        {
            Response.Redirect("AdminList.aspx?sucmsg=恭喜。解锁成功。");
        }
    }
    #endregion

    #region 权限列表
    int EmptyNum = 0;
    protected string GetRoleFlagList()
    {
        StringBuilder xs = new StringBuilder();
        DataTable dt = bllAdmin.GetRoleChildFlag(0).Tables[0];
        for (int i = 0; i < dt.Rows.Count; i++)
        {
            EmptyNum = 0;
            xs.AppendFormat("<div id=\"p{0}\"><ul class=\"ultitle\" id=\"t{0}\"><input type=\"checkbox\" name=\"RoleFlag\" id=\"{0}\"  value=\"{3}\" onclick=\"selAll(this.id)\">" +
                "<img align=\"absmiddle\" src=\"/Manage/pic/menu/{2}\"/>&nbsp;<span id=\"s{0}\"onclick=\"showchildnode(this.id)\" style=\"cursor:pointer;\">{1}</span></ul>",
                dt.Rows[i][0].ToString(), dt.Rows[i][1].ToString(), dt.Rows[i][3].ToString(), dt.Rows[i][4].ToString());
            xs.Append(GetChildRoleFlagList(Convert.ToInt32(dt.Rows[i][0])));
            xs.Append("</div>");
        }
        return xs.ToString();
    }
    private string GetChildRoleFlagList(int pID)
    {
        string xs = "";
        for (int n = 0; n < EmptyNum; n++)
        {
            xs += "　";
        }
        StringBuilder strRFlaglist = new StringBuilder();
        if (EmptyNum == 0)
        {
            strRFlaglist.Append("<ul class=\"divurl\" id=\"c" + pID + "\" style=\"border:1px solid #99CCFF;\">");
        }
        else
        {
            strRFlaglist.Append("<ul class=\"divurl\" id=\"c" + pID + "\">");
        }
        DataTable dtChild = bllAdmin.GetRoleChildFlag(pID).Tables[0];
        for (int m = 0; m < dtChild.Rows.Count; m++)
        {
            strRFlaglist.AppendFormat("<li>" + xs + "<input type=\"checkbox\"  name=\"RoleFlag\" id=\"{0}\" value=\"{3}\" onclick=\"conclick(this.id," + pID + ")\">" +
                "<img align=\"absmiddle\" src=\"/Manage/pic/menu/{2}\"/>&nbsp;{1}</li>", dtChild.Rows[m][0].ToString(), dtChild.Rows[m][1].ToString(),
                dtChild.Rows[m][3].ToString().ToLower() == "" ? "item.gif" : dtChild.Rows[m][3].ToString(), dtChild.Rows[m][4].ToString());
            if (dtChild.Rows[m]["HaveChildNav"].ToString().ToLower() == "true")
            {
                EmptyNum++;
                strRFlaglist.Append(GetChildRoleFlagList(Convert.ToInt32(dtChild.Rows[m][0])));
            }
        }
        strRFlaglist.Append("</ul>");
        return strRFlaglist.ToString();
    }
    #endregion

    #region 改变下面站点选择状态
    private void ChageSiteRoleFlagState()
    {
        string StrRet = "";
        string RoleIDs = PageRequest.GetString("IDs");
        int userID = PageRequest.GetInt("userID", -1);
        KeRui.BLL.AdminRole bllAdminRole = new KeRui.BLL.AdminRole();
        List<KeRui.Model.AdminRole> listAdminRole = bllAdminRole.GetList(RoleIDs);
        string RoleFlags = ",";
        foreach (KeRui.Model.AdminRole model in listAdminRole)
        {
            if (model.RoleFlag != "")
            {
                RoleFlags += model.RoleFlag + ",";
            }
        }

        modelAdmin = bllAdmin.GetModel(userID);
        string strTmp = "";
        if (modelAdmin != null)
        {
            strTmp = "," + modelAdmin.PlusFlag + ",";
        }
        StrRet = KeRui.BLL.Common.GetCheckBoxListForSite("SiteID", RoleFlags, strTmp, bllCmsSite.GetCmsSiteChk());
        Response.Write(StrRet); Response.End();
    }


    #endregion

    #region 显示该管理员所拥有的权限站点
    private void showSite()
    {
        string StrRet = "";
        int userID = PageRequest.GetInt("id", -1);
        modelAdmin = bllAdmin.GetModel(userID);
        if (modelAdmin == null)
        {
            Response.Write("Error：没有找到ModelAdmin"); Response.End();
        }
        KeRui.BLL.CmsSite bllCmsSite = new KeRui.BLL.CmsSite();
        List<KeRui.Model.CmsSite> list = bllCmsSite.GetList();
        modelAdmin.UserFlag = "," + modelAdmin.UserFlag + ",";
        foreach (KeRui.Model.CmsSite model in list)
        {
            if (modelAdmin.UserFlag.IndexOf(",site_" + model.SiteID + ",") != -1)
            {
                StrRet += "<li><a href=\"AdminSiteRole.aspx?siteid=" + model.SiteID + "&userid=" + userID + "\">" + model.SiteName + "</a></li>";
            }
        }
        if (StrRet == "")
        {
            StrRet = "没有分配站点。";
        }
        Response.Write(StrRet); Response.End();
    }
    #endregion

    private void ShowAdditionalrights()
    {
        string StrRet = "";
        KeRui.BLL.SysConfig bllSysConfig = new KeRui.BLL.SysConfig();
        List<KeRui.Model.SysConfig> listSysConfig;
        listSysConfig = bllSysConfig.GetList("Additionalrights", 0);
        foreach (KeRui.Model.SysConfig modelSysConfig in listSysConfig)
        {
            StrRet += "<li><a href=\"PlusFlag.aspx?userID=" + AccountID + "&flagType="+modelSysConfig.Value+"\">" + modelSysConfig.Name + "</a></li>";
        }
        if (StrRet == "")
        {
            StrRet = "没有权限。";
        }
        Response.Write(StrRet); Response.End();
    }
}
